package com.wica.media;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import com.commonsware.android.advservice.IScript;
import com.wica.facetube.R;
import com.wica.view.Rating;

public class CopyOfPlayer extends Activity implements MediaPlayer.OnPreparedListener,
		MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {

	// *************** Constants ************** //
	// Log constants
	private static final String LOG_TAG = "PTv.Player";
	// Identifiers for our menu items.
	private static final int RATE_CURRENT_VIDEO = Menu.FIRST;
	// Context.startActivityForResult request code
	private static final int RATING_START_ACTIVITY_FOR_RESULT_REQUESTCODE = 0;

	// *************** Attributes ************************* //
	private VideoView videoView;
	private MediaController mediaController;
	private Dialog dialog;
	private Intent intent;
	private int rating = 0;

	private IScript service = null;
	private ServiceConnection svcConn = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder binder) {
			service = IScript.Stub.asInterface(binder);
		}

		public void onServiceDisconnected(ComponentName className) {
			service = null;
		}
	};
	private String laurl;
	private String date_uuid;
	protected boolean stopped = false;
	protected int extasu = 99;
	private boolean buleanoo;
	private boolean homebuttonpressed;
	private boolean notalreadyrated=true;
	private String activity;

	// *************** Methods **************************** //

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		homebuttonpressed=true;

		// We inflate layout from /layout/videoview
		setContentView(R.layout.videoview);

		// we bind to svcConn (ServiceConnection we created) to invoke
		// startMonitoring & stopMonitoring
		buleanoo = bindService(new Intent(IScript.class.getName()), svcConn,Context.BIND_AUTO_CREATE);
		while (!buleanoo) {
			Log.e(LOG_TAG, "en el bucle del binding");
			buleanoo = bindService(new Intent(IScript.class.getName()),
					svcConn, Context.BIND_AUTO_CREATE);
		}

		activity = this.getIntent().getExtras().get("app_activity").toString();
		Log.v(LOG_TAG, activity);
		// we display progress dialog
		Thread t = new Thread() {
			public void run() {
			}
		};
		t.start();
		if (dialog == null) {
			dialog = this.onCreateDialog(1);
			dialog.show();
		}
		date_uuid = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(
				Calendar.getInstance().getTime()).toString()
				+ "__"
				+ PreferenceManager.getDefaultSharedPreferences(this).getInt(
						"userID", -1);
		;

		videoView = (VideoView) findViewById(R.id.surface_view);
		intent = this.getIntent();
		// Alternatively,for streaming media you can use
		// videoView.setVideoURI(Uri.parse(URLstring));
		videoView.setVideoPath(intent.getDataString());
		Log.v(LOG_TAG, intent.getDataString());

		mediaController = new MediaController(this);

		// mediaController.set
		videoView.pause();
		videoView.setMediaController(mediaController);
		videoView.requestFocus();
		// videoView.setOnClickListener(l)

		videoView.setOnPreparedListener(this);
		videoView.setOnCompletionListener(this);
		videoView.setOnErrorListener(this);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		// RSSI
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		if (telephonyManager != null) {
			telephonyManager.listen(new PhoneStateListener() {
				@Override
				public void onSignalStrengthChanged(int asu) {
					GregorianCalendar time_calendar = new GregorianCalendar(
							TimeZone.getTimeZone(Time.getCurrentTimezone()),
							Locale.getDefault());
					long epoch = time_calendar.getTime().getTime();
					Log.v(LOG_TAG, "RSSI at epoch (" + epoch + "):" + asu);
					if (service != null) {
						try {
							service.storeRSSI(asu);
						} catch (RemoteException e) {
							// TODO Auto-generated catch block
							Log.e(LOG_TAG, "RemoteException" + e.getMessage());
							e.printStackTrace();
						}						
					}
				};
			}, PhoneStateListener.LISTEN_SIGNAL_STRENGTH);
		}
	}// onCreate method

	@Override
	protected void onPause() {
		super.onPause();
				if (homebuttonpressed)
			finish();
		
	}
	
	@Override
	public void onPrepared(MediaPlayer mp) {
		mp.setOnErrorListener(this);
		Log.v(LOG_TAG, "onPrepared");
		date_uuid = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(
				Calendar.getInstance().getTime()).toString()
				+ "__"
				+ PreferenceManager.getDefaultSharedPreferences(this).getInt(
						"userID", -1);
		;
		startMonitoring(date_uuid);
		videoView.requestFocus();
		Log.v(LOG_TAG, "wait");		
		Log.v(LOG_TAG, "play");
		videoView.start();
		// this.getIntent().getExtras().get("URL").toString()
		// date_uuid = new
		// SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(Calendar.getInstance().getTime()).toString()+"__"+UUID.randomUUID().toString();
		if (dialog != null)
			dialog.dismiss();
	}// onPrepared method (MediaPlayer.OnPreparedListener)

	public boolean onKeyDown(int keyCode, KeyEvent event) {
			homebuttonpressed=false;
	
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			stopMonitoring();
			forceRating();
			return true;				
		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			Log.v(LOG_TAG,"u pressed home");
			homebuttonpressed=true;
			return super.onKeyDown(keyCode, event);
		} else
			return super.onKeyDown(keyCode, event);		
	}// onKeyDown method

	private void invokeSurvey() {
		Intent intent4 = new Intent("net.sylvek.test.HISTORY");
		intent4.putExtra("formpath", FORMPATH);
		intent4.putExtra("outputpath", "/sdcard/wica_files/"+ date_uuid);
		intent4.putExtra("rating_given",((rating <= 2 && rating != 0) ? 'y' : 'n'));
		this.startActivity(intent4);
	}

	private void stopMonitoring() {
		Thread t = new Thread() {
			public void run() {
				try {
					if (service != null) {
						service.stopMonitoring("url", 1);
					} else {
						bindService(new Intent(IScript.class.getName()),
								svcConn, Context.BIND_AUTO_CREATE);
						if (service != null)
							service.stopMonitoring("url", 1);
					}
				} catch (android.os.RemoteException e) {
				}
			}
		};
		t.start();
	}

	IScript service2 = null;
	private final String FORMPATH = "/sdcard/wica_files/WicaFormTest.xml";
	private int currentPosition;

	private void createAppParametersFile(String url) {
		laurl = url;
		currentPosition = videoView.getCurrentPosition();
		Thread t = new Thread() {
			public void run() {
				try {
					if (service != null) {
						service.createAppParametersFile(
								getAppParametersLabel(), getAppParameters());
					} else {
						bindService(new Intent(IScript.class.getName()),
								svcConn, Context.BIND_AUTO_CREATE);
						if (service != null)
							service
									.createAppParametersFile(
											getAppParametersLabel(),
											getAppParameters());
					}

					finish();
					stopped = true;
				} catch (android.os.RemoteException e) {
				}

			}

			private String getAppParametersLabel() {
				return "app_name;app_activity;app_activity_time;position;HTTP_video_URL;RTSP_video_URL;videoLength;percentage_watched;title;category;tags;rating;total_rating;mood;location;device_id";
			}
		};
		t.start();

	}

	private void startMonitoring(String url) {
		laurl = url;

		Thread t = new Thread() {
			public void run() {
				try {
					if (service != null) {
						service.executeScript(laurl, extasu);
					} else {
						bindService(new Intent(IScript.class.getName()),
								svcConn, Context.BIND_AUTO_CREATE);
						if (service != null)
							service.executeScript(laurl, extasu);
					}
				} catch (android.os.RemoteException e) {
					Log.v(LOG_TAG, "remote exception");
				}

			}
		};
		t.start();
	}

	protected String getAppParameters() {
		// GPS_location_sent;youtube_server_ip
		Log.v(LOG_TAG, "" + videoView.getCurrentPosition());
		Log.v(LOG_TAG, "" + videoView.getDuration());
		SharedPreferences sp = PreferenceManager
				.getDefaultSharedPreferences(this);
		String app_parameters_string = "androidpersonaltv" + ";";
		app_parameters_string = app_parameters_string
				+ this.getIntent().getExtras().get("app_activity").toString()
				+ ";";
		app_parameters_string = app_parameters_string
				+ this.getIntent().getExtras().get("app_activity_time")
						.toString() + ";";
		app_parameters_string = app_parameters_string
				+ this.getIntent().getExtras().get("position").toString() + ";";
		app_parameters_string = app_parameters_string
				+ this.getIntent().getExtras().get("URL").toString() + ";";
		app_parameters_string = app_parameters_string
				+ this.getIntent().getDataString() + ";";
		app_parameters_string = app_parameters_string + videoView.getDuration()
				+ ";";
		app_parameters_string = app_parameters_string + (currentPosition * 100)
				/ videoView.getDuration() + ";";
		app_parameters_string = app_parameters_string
				+ this.getIntent().getExtras().get("title").toString() + ";";
		app_parameters_string = app_parameters_string
				+ this.getIntent().getExtras().get("category_tags").toString()
				+ ";";
		app_parameters_string = app_parameters_string + rating + ";";
		app_parameters_string = app_parameters_string
				+ this.getIntent().getExtras().get("totalRating").toString()
				+ ";";
		app_parameters_string = app_parameters_string
				+ sp.getString("mood", "Happy") + ";";
		app_parameters_string = app_parameters_string
				+ sp.getString("text_location", "at_home") + ";";
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		app_parameters_string = app_parameters_string
				+ telephonyManager.getDeviceId() + ";";
		return app_parameters_string;
	}

	protected boolean internetNetworkAvailable() {
		// Local Variables
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] allNetworkInfo = connectivityManager.getAllNetworkInfo();
		int i;

		for (i = 0; i < allNetworkInfo.length; i++) {
			NetworkInfo networkInfoItem = allNetworkInfo[i];
			if (networkInfoItem.isAvailable()) {
				return true;
			}// if
		}// for
		return false;
	}// internetNetworkAvailable method

	@Override
	public void onCompletion(MediaPlayer mp) {
		Log.v(LOG_TAG, "oncompletion");
		homebuttonpressed=false;		
		if (!internetNetworkAvailable())
			finish();
		stopMonitoring();
		forceRating();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 1:
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("Please wait while loading...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.setOnKeyListener(new OnKeyListener() {
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode,
						KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_BACK) {
						finish();
						return true;
					} else {
						return false;
					}// if
				}// onKey method
			});
			return dialog;
		case 2:
			return new AlertDialog.Builder(this)
					.setIcon(R.drawable.stat_sample).setTitle(
							"Sorry cannot play video").setMessage(
							"Check your data connection and try again")
					.setPositiveButton(R.string.alert_dialog_ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									onKeyDown(KeyEvent.KEYCODE_BACK,null);
								}// onclick method
							}).create();
		}
		return dialog;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.v(LOG_TAG,"onActivityResult:"+activity);
		if (requestCode == 90){
			if (activity.compareTo("ELSuggestions")==0){
				invokeSurvey();
			}
			createAppParametersFile(this.getIntent().getExtras().get("URL").toString());
		}		
	}// onActivityResult method

	@Override
	public void onDestroy() {
		super.onDestroy();
		stopMonitoring();
		if (!stopped) {
			createAppParametersFile(this.getIntent().getExtras().get("URL").toString());
		}
		unbindService(svcConn);
	}// onDestroy method

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		showDialog(2);
		return true;
	}
	
	public void forceRating(){
		Log.v(LOG_TAG,"force rating");
		Intent i = (new Intent(CopyOfPlayer.this, Rating.class));
		i.putExtra("URL", this.getIntent().getExtras().get("URL")
				.toString());
		i.putExtra("URLThumbnail", this.getIntent().getExtras().get(
				"URLThumbnail").toString());
		i.putExtra("totalRating", this.getIntent().getExtras().get(
				"totalRating").toString());
		i.putExtra("title", this.getIntent().getExtras().get("title")
				.toString());
		i.putExtra("rating", rating);
		i.putExtra("scape", "notscape");
		this.startActivityForResult(i, 90);
	}

}// Player class